<template>
  <form class="image-input-wrapper">
    <div class="image-submit-cover">
      <img
        ref="cover"
        :src="imageUrl"
        alt="image"
        v-show="imageUrl"
        class="cover-image"
      />
      <span v-show="!imageUrl">upload</span>
    </div>
    <input
      type="file"
      name="image"
      class="image-input"
      ref="imageInput"
      @input="handleInput($event)"
    />
  </form>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
const emit = defineEmits<{
  (e: 'update:image', file: File): void
}>()

const props = defineProps<{
  image: File
}>()

let imageUrl = ref('')
watch(
  () => {
    return props.image
  },
  (newVal) => {
    if (!newVal) {
      imageUrl.value = ''
      return
    }
    if (!((newVal as any) instanceof Blob)) return
    let reader = new FileReader()
    reader.addEventListener('load', () => {
      imageUrl.value = reader.result as string
    })
    reader.readAsDataURL(props.image)
  }
)

function handleInput(event: Event) {
  emit('update:image', (event.target as any).files[0])
}
</script>

<style lang="scss" scoped>
@import 'style/shortcut';
$w: $imageInputWidth;
$h: $imageInputHeight;

.image-input-wrapper {
  position: relative;
  width: $w;
  height: $h;

  .image-input {
    display: block;
    width: $w;
    height: $h;

    position: absolute;
    top: 0;
    left: 0;

    opacity: 0;

    &:hover {
      cursor: pointer;
    }
  }

  .image-submit-cover {
    box-sizing: border-box;
    position: relative;
    width: $w;
    height: $h;
    line-height: $h;
    text-align: center;
    border-radius: calc($w * 0.05);
    border: 1px dashed var(--gray);
    color: var(--gray);
    transition: 0.1s;

    .cover-image {
      width: calc($w * 1.1);
      height: calc($h * 1.1);
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border-radius: calc($w * 0.02);
    }
  }

  &:hover {
    .image-submit-cover {
      color: var(--darkBlue);
      border-color: var(--darkBlue);
    }
  }
}
</style>
